package com.example.a0521;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.a0521.fragments.AlbumDetailFragment;
import com.example.a0521.pojo.Album;

import java.util.List;

//生成一个适配器
public class AlbumAdpater extends ArrayAdapter<Album> {
    private int resource;

    public AlbumAdpater(@NonNull Context context, int resource, @NonNull List<Album> albums) {
        super(context, resource, albums);
        this.resource = resource;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        Album album = getItem(position);
        //是利用传入的布局，创造一个视图对象
        convertView = LayoutInflater.from(getContext()).inflate(resource, parent, false);
        //将集合中的数据与视图中的组件进行绑定
        TextView tv = convertView.findViewById(R.id.name);
        //获取price的内容
        TextView priceTv = convertView.findViewById(R.id.priceTv);
        //找到Button id
        Button detailBtn = convertView.findViewById(R.id.detailBtn);
        //暂存现场数据,使用setTag
        detailBtn.setTag(album);

        tv.setText(album.getName());
        priceTv.setText(album.getPrice() + "");
        //给Buttin添加事件
        detailBtn.setOnClickListener(v -> switchDetail(v));
        return convertView;
    }

    //制造按钮点击方法
    private void switchDetail(View v) {
        //img数据抓取
        Bundle bundle = new Bundle();
        //取得现场数据
        Album album = (Album) v.getTag();
        bundle.putInt("id",album.getId());
        //强转成Activity的父类
        AppCompatActivity activity = (AppCompatActivity) getContext();
        activity.getSupportFragmentManager().beginTransaction()
                .replace(R.id.container, AlbumDetailFragment.class, bundle)
                //回退栈
                .addToBackStack(null)
                .commit();

    }
}
